﻿
using System.Collections.Generic;
using System;

namespace Ops.Mpc.Ioc
{
    /// <summary>
    /// Simple service locator class
    /// </summary>
    public class IocServiceLocator
    {
        #region Properties
        private static readonly Dictionary<Type, object> _registrations = new Dictionary<Type, object>();
        private static readonly object _lock = new object();
        #endregion 

        #region Static Methods
        /// <summary>
        /// Registers the given instance for the interface type.
        /// </summary>
        /// <typeparam name="InterfaceType">The type of the interface to register the given instance for</typeparam>
        /// <param name="instance">The instance that impliments the interface</param>
        public static void Register<InterfaceType>(InterfaceType instance) where InterfaceType : class
        {
            lock (_lock)
            {
                if (!_registrations.ContainsKey(typeof(InterfaceType)))
                    _registrations.Add(typeof(InterfaceType), instance);
                else
                    throw new Exception(string.Format("Locator already has registration for {0}", typeof(InterfaceType).FullName));
            }
        }

        /// <summary>
        /// Returns an object instance that impliments the service type
        /// </summary>
        /// <typeparam name="InterfaceType">The interface type to return an instance for</typeparam>
        /// <returns></returns>
        public static InterfaceType Get<InterfaceType>() where InterfaceType : class
        {
            lock (_lock)
            {
                if (_registrations.ContainsKey(typeof(InterfaceType)))
                    return _registrations[typeof(InterfaceType)] as InterfaceType;
                else
                    return null;
            }
        }

        /// <summary>
        /// This clears the registration for the interface type
        /// </summary>
        /// <typeparam name="InterfaceType">The interface type to clear</typeparam>
        public static void Clear<InterfaceType>()
        {
            lock (_lock)
            {
                if (_registrations.ContainsKey(typeof(InterfaceType)))
                    _registrations.Remove(typeof(InterfaceType));
            }
        }

        #endregion

  
    }
}
